<template>
  <div class="app-container">
    <div class="contract-search">
      <!-- <div class="contract-btns">
        <el-button @click="createByTemplate">模板发起合同</el-button>
        <el-button @click="createByFile">文件发起合同</el-button>
      </div> -->
      <el-input clearable placeholder="请输入合同名称" v-model="keyword" @change="onSearchInput" style="width: 360px">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </div>

    <el-table
      v-loading="listLoading"
      :data="contractList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="合同ID" width="200">
        <template slot-scope="scope">
          {{ scope.row.FlowId }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="合同类型" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.FlowType || '未分类' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同名称">
        <template slot-scope="scope">
          {{ scope.row.FlowName }}
        </template>
      </el-table-column>
      <el-table-column label="企业ID" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发起人" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.FlowApproverInfos[0].ProxyOrganizationName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签署人" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ getSignName(scope.row) }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="签署状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row)" size="small">{{ FLOW_STATUS_TEXT[scope.row.FlowStatus] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_time" label="发起时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ moment(scope.row.CreateOn * 1000).format('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="end_time" label="截止时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ moment(scope.row.DeadLine * 1000).format('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.FlowStatus === FLOW_STATUS.INIT"
            type="text"
            size="small"
            @click="onSignClick(scope.row)"
            >发起签署</el-button
          >
          <!-- <el-button type="text" size="small" v-if="scope.row.FlowStatus !== FLOW_STATUS.ALL">取消</el-button> -->
          <el-button type="text" size="small" @click="onShowDetail(scope.row)">查看详情</el-button>
          <el-button type="text" size="small" @click="onSettingFlowType(scope.row)">设置合同类型</el-button>
          <!-- 签署中才显示撤销按钮 -->
          <el-button v-if="scope.row.FlowStatus === 'PART'" type="text" size="small" @click="cancelFlow(scope.row)"
            >撤销</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" :total="1000"> </el-pagination>

    <el-dialog
      title="文件发起合同"
      :visible.sync="dialogVisibleFile"
      width="30%"
      :before-close="onDialogClose"
      :close-on-click-modal="false"
    >
      <div>
        <el-upload
          class="upload-demo"
          ref="upload"
          drag
          :limit="100"
          :file-list="fileList"
          action="#"
          :http-request="executeUpload"
          :auto-upload="false"
          :before-upload="beforeExcelUpload"
          :on-change="onUploadChange"
          :before-remove="onRemoveItem"
          accept=".pdf,.jpg,.png,.doc,.docx,.html,.jpeg"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">文件最大支持100M</div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFile = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitUpload">确定提交并发起</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="设置签署截止日期"
      :visible.sync="dialogVisibleSign"
      width="30%"
      :before-close="onCloseSignDialog"
      :close-on-click-modal="false"
    >
      <div>
        <el-date-picker v-model="deadLine" type="date" placeholder="选择截止日期" style="width: 100%"> </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSign = false">取 消</el-button>
        <el-button type="primary" @click="onSign">确定并发起签署</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="设置合同类型"
      :visible.sync="dialogVisibleFlowType"
      width="30%"
      :before-close="() => (dialogVisibleFlowType = false)"
      :close-on-click-modal="false"
    >
      <div>
        <el-select v-model="currentFlowType" placeholder="请选择合同类型" style="width: 100%">
          <el-option v-for="item in flowTypes" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFlowType = false">取 消</el-button>
        <el-button type="primary" @click="onModifyFlowType">确认修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  signContractByFile,
  getContractList,
  createSignUrl,
  updateContract,
  channelCancelFlow,
} from '@common/api/contract';
import { FLOW_STATUS_TEXT, FLOW_STATUS } from '@common/consts/status';

import moment from 'moment';

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      moment,
      contractList: [],
      listLoading: false,
      dialogVisibleFile: false,
      dialogVisibleSign: false,
      fileList: [],
      uploadList: [],
      templateList: [],
      templateId: {},

      keyword: '',
      currentPage: 1,
      pageSize: 2,
      FLOW_STATUS,
      FLOW_STATUS_TEXT,
      // 设置合同类型
      flowTypes: [
        {
          value: '分销合同',
          label: '分销合同',
        },
        {
          value: '承诺/授权',
          label: '承诺/授权',
        },
        {
          value: '服务/合作',
          label: '服务/合作',
        },
        {
          value: '租赁',
          label: '租赁',
        },
        {
          value: '采购/销售',
          label: '采购/销售',
        },
        {
          value: '人事/劳动',
          label: '人事/劳动',
        },
        {
          value: '其他',
          label: '其他',
        },
      ],
      currentFlowType: '',
      currentRow: {},
      dialogVisibleFlowType: false,
      deadLine: moment().unix(),
      searchText: '',
    };
  },
  created() {
    this.fetchContractList();
  },
  methods: {
    onSearchInput(value) {
      this.searchText = value;
    },
    onShowDetail(row) {
      this.$router.push(`/contract/detail/${row.FlowId}`);
    },
    getSignName(row) {
      const flowInfos = row.FlowApproverInfos || [];
      const signersInfos = flowInfos.filter(item => item.ApproveType === 'PERSON');

      const signs = [];

      signersInfos.forEach(item => {
        signs.push(item.ApproveName);
      });
      return signs.join(',');
    },
    async onModifyFlowType() {
      if (!this.currentFlowType) return;
      updateContract({
        ...this.currentRow,
        FlowType: this.currentFlowType,
      }).then(() => {
        this.fetchContractList();
        this.dialogVisibleFlowType = false;
      });
    },
    async onSettingFlowType(row) {
      this.currentRow = row;
      this.currentFlowType = row.FlowType;
      this.dialogVisibleFlowType = true;
    },
    getTagType(row) {
      const flowStatus = row.FlowStatus;
      switch (flowStatus) {
        case FLOW_STATUS.INIT:
          return 'info';
        case FLOW_STATUS.PART:
          return '';
        case FLOW_STATUS.ALL:
          return 'success';
        case FLOW_STATUS.REJECT:
          return 'warning';
        case FLOW_STATUS.EXCEPTION:
          return 'danger';
        default:
          return 'warning';
      }
    },
    async onSignClick(row) {
      this.currentRow = row;
      this.dialogVisibleSign = true;
    },
    async onSign() {
      this.dialogVisibleSign = false;
      // 先更新DeadLine
      // 再发送短信
      updateContract({ ...this.currentRow, DeadLine: this.deadLine }).then(async () => {
        const res = await createSignUrl(this.currentRow);
        if (res?.data?.SignUrlInfos?.length) {
          this.$alert(res?.data?.SignUrlInfos[0].SignUrl, '短信链接', {
            confirmButtonText: '确定',
          });
        }
      });
    },
    onDialogClose() {
      this.dialogVisibleFile = false;
    },
    fetchContractList() {
      getContractList().then(res => {
        this.contractList = res.data;
      });
    },

    onCloseSignDialog() {
      this.dialogVisibleSign = false;
    },

    // 模板发起合同
    createByTemplate() {
      this.$router.push('/template');
    },

    onRemoveItem(info) {
      this.uploadList = this.uploadList.filter(item => item.uid !== info.uid);
    },
    beforeExcelUpload() {},
    executeUpload(_params) {
      const promises = [];

      const toBase64Promise = item =>
        new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(item.raw);
          reader.onload = e => {
            resolve({
              FileBody: e.target.result.split(',')[1],
              FileName: item.name,
            });
          };
          reader.onerror = err => {
            console.log(err);
            reject();
          };
        });

      this.uploadList.map(item => {
        promises.push(toBase64Promise(item));
      });

      Promise.all(promises).then(results => {
        signContractByFile({
          BusinessType: 'TEMPLATE',
          FileInfos: results,
        })
          .then(res => {
            console.log(res, 'res====x');
            this.fetchContractList();
            this.onDialogClose();
          })
          .catch(e => console.log(e));
      });
    },
    onUploadChange(file, fileList) {
      // 判断 > 1M
      // if (file.size > 1048576) {
      //   fileList.pop();
      //   let msg_size = `您上传的${file.name}，该文件大于1M，请您重新上传。`;
      //   this.notify_self(msg_size, "size");
      //   return false;
      // }
      // 判断重名文件
      const repeatJudge = this.fileList.find(item => item.name === file.name);
      if (repeatJudge) {
        fileList.pop();
        // let msgRepeat = `您上传的${file.name}，该文件有重名文件，请您重新上传。`;
        return false;
      }
      this.fileList = JSON.parse(JSON.stringify(fileList));
      this.uploadList.push(file);
      console.log(this.uploadList, 'this.uploadList===');
    },
    onSubmitUpload() {
      if (!this.uploadList.length) {
        this.$message('请选择一个文件');
        return;
      }
      this.$refs.upload.submit();
    },
    // 文件发起合同
    createByFile() {
      this.dialogVisibleFile = true;
    },

    // 撤销流程
    async cancelFlow(data) {
      // console.log('data', data);
      if (data?.FlowId) {
        const response = await channelCancelFlow({ FlowId: data?.FlowId });
        console.log('response===', response);
        if (response?.code === 20000 && response?.data?.RequestId) {
          this.$message({ message: '撤销流程成功', type: 'success' });
          this.fetchContractList();
        } else {
          this.$message.error('撤销流程失败');
        }
      }
    },
  },
};
</script>

<style lang="scss">
.contract-search {
  text-align: right;
  padding-bottom: 20px;
  // display: flex;
  // justify-content: space-between;
  // .contract-btns {
  //   position: relative;
  //   margin-bottom: 20px;
  // }
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}
</style>
